import easyocr
import cv2
import time
def ocr_with_easyocr(img,reader = None,roi = None,bbox = False):
    """
    使用 EasyOCR 识别 OpenCV 图片中的文字
    :param img: numpy.ndarray (BGR 格式)
    :param reader: EasyOCR 
    :param roi: 感兴趣区域，格式为 (x, y, width, height)，x 和 y 是区域左上角坐标，width 和 height 是区域的宽和高
    :param bbox: 是否不需要返回识别的边框
    :return: 识别结果 (str)
    """
    if reader is None:
        # 初始化 EasyOCR ，支持中文和英文，并指定使用 GPU（gpu=True）
        reader = easyocr.Reader(['ch_sim', 'en'], gpu=True)

    if roi is not None:
        x, y, w, h = roi
        # 边界保护
        x, y = max(0, x), max(0, y)
        w = min(w, img.shape[1] - x)
        h = min(h, img.shape[0] - y)
        if w <=0 or h <=0:
            return ""
        img = img[y:y+h, x:x+w]

    # 识别文字
    result = reader.readtext(img)
    
    if bbox:
        text = ",".join([line[1] for line in result])
        return text

    # 整合文字和边框位置到对象数组
    text_and_bbox = []
    for line in result:
        bbox = line[0]
        text = line[1]
        # 计算 x, y, w, h
        x = int(min([point[0] for point in bbox]))
        y = int(min([point[1] for point in bbox]))
        max_x = int(max([point[0] for point in bbox]))
        max_y = int(max([point[1] for point in bbox]))
        w = max_x - x
        h = max_y - y
        item = {
            "text": text,
            "bbox": (x,y,w,h)
        }
        text_and_bbox.append(item)
    return text_and_bbox